package material

// 临时素材管理.

import (
    "fmt"
	"io"
	"encoding/json"
	"wxsdk/miniapp/core"
	//"github.com/astaxie/beego"
)

const (
	MaterialGetTemporaryURL    = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=%s&media_id=%s"
	MaterialUploadTemporaryURL = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=%s&type=%s"
)

//MediaType 媒体文件类型
//type MediaType string

// CommonError 微信返回的通用错误json
type CommonError struct {
	ErrCode int64  `json:"errcode"`
	ErrMsg  string `json:"errmsg"`
}

// GetTemporaryMaterial 查询临时素材
func GetTemporaryMaterial(accessToken,mediaId string) (headPara map[string]string,body []byte,err error) {
	url := fmt.Sprintf(MaterialGetTemporaryURL, accessToken, mediaId)
	return core.GetFileByHttp(url)
}

//Media 临时素材上传返回信息
type Media struct {
	CommonError
	Type      string    `json:"type"`
	MediaId   string    `json:"media_id"`
	//ThumbMediaID string `json:"thumb_media_id"`
	CreatedAt int64     `json:"created_at"`
}

//基于文件名称上传临时素材
func  MediaUploadByName(accessToken, mediaType string, filename string) (media Media, err error) {
	url := fmt.Sprintf(MaterialUploadTemporaryURL, accessToken, mediaType)
	var response []byte
	response, err = core.PostFileByName(url, "media", filename)
	if err != nil {
		return
	}
	err = json.Unmarshal(response, &media)
	if err != nil {
		return
	}
	if media.ErrCode != 0 {
		err = fmt.Errorf("MediaUpload error : errcode=%v , errmsg=%v", media.ErrCode, media.ErrMsg)
		return
	}
	return
}

//基于文件内容上传临时素材
func  MediaUploadByData(accessToken, mediaType string, data []byte) (media Media, err error) {
	url := fmt.Sprintf(MaterialUploadTemporaryURL, accessToken, mediaType)
	var response []byte
	virtualFileName := "tmp.jpg"
	response, err = core.PostFileByData(url, "media", virtualFileName, data)
	if err != nil {
		return
	}
	err = json.Unmarshal(response, &media)
	if err != nil {
		return
	}
	if media.ErrCode != 0 {
		err = fmt.Errorf("MediaUpload error : errcode=%v , errmsg=%v", media.ErrCode, media.ErrMsg)
		return
	}
	return
}

func  MediaUploadByIoReader(accessToken, mediaType string, input io.Reader) (media Media, err error) {
	url := fmt.Sprintf(MaterialUploadTemporaryURL, accessToken, mediaType)
	var response []byte
	virtualFileName := "tmp.jpg"
	response, err = core.PostFileByIoReader(url, "media", virtualFileName, input)
	if err != nil {
		return
	}
	err = json.Unmarshal(response, &media)
	if err != nil {
		return
	}
	if media.ErrCode != 0 {
		err = fmt.Errorf("MediaUpload error : errcode=%v , errmsg=%v", media.ErrCode, media.ErrMsg)
		return
	}
	return
}


